package fi.helsinki.cs.ohtu10k.schedule;

import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.io.ObjectOutputStream;
import java.io.ObjectInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * Handler for manager singleton.
 * @author Thomas Nyman
 * @author Jani Rönkä
 *
 */
public final class ScheduleManagerHandler {
	private static ScheduleManager manager;
	
	/**
	 * Returns the manager.
	 * @return The manager.
	 */
	public static ScheduleManager getScheduleManager() {
		return (manager != null ? manager : (manager = new PeriodManager()));
	}
	
	/**
	 * Saves managed schedule to specified file. 
	 * @param filename Name of target file.
	 * @throws FileNotFoundException
	 * @throws IOException
	 */
	public static void saveSchedule(String filename) throws FileNotFoundException, IOException {
		ObjectOutputStream outstream = new ObjectOutputStream(new FileOutputStream(filename));
		outstream.writeObject(manager);
		outstream.close();
	}
	
	/**
	 * Loads saved schedule from specified file.
	 * @param filename Name of source file.
	 * @throws FileNotFoundException
	 * @throws ClassNotFoundException
	 * @throws IOException
	 */
	public static void loadSchedule(String filename) throws FileNotFoundException, ClassNotFoundException, IOException {
		ObjectInputStream instream = new ObjectInputStream(new FileInputStream(filename));
		manager = (PeriodManager)instream.readObject();
		instream.close();
	}
	
	/**
	 * Resets the manager.
	 */
	public static void resetScheduleManager() {
		manager = null;
	}

}
